
//Contain the JSON definition of the message 
var data;




var inputTree;

YAHOO.widget.Logger.enableBrowserConsole();


function showHideSection(divId) {
var div = document.getElementById(divId);	
if(div.style.display == "none") {
	div.style.display = '';
	document.getElementById(divId + 'ShowHideSectionBox').className = 'hideSection';
}	
else {
	div.style.display = 'none';
	document.getElementById(divId + 'ShowHideSectionBox').className = 'showSection';
}
}

function initData() {
    data = YAHOO.lang.JSON.parse(document.getElementById('messageJSONDef').innerHTML);
}

function inputTreeInit() { 
inputTree = new YAHOO.drafTrack.tableTree("treeInput",oInputConfigs); var root = inputTree.getRoot(); 

inputTree.loadNodes(data.inputDefinition,root);inputTree.draw(); 

}


function outputTreeInit() { 
outputTree = new YAHOO.drafTrack.tableTree("treeOutput",oOutputConfigs); var root = outputTree.getRoot(); 

outputTree.loadNodes(data.outputDefinition,root);outputTree.draw(); 

}


	


YAHOO.util.Event.onDOMReady(initData);
YAHOO.util.Event.onDOMReady(inputTreeInit); 
YAHOO.util.Event.onDOMReady(outputTreeInit); 



//Add a clone function to the object to allow the cloning of nodes to decorelate them from the defaultNode
function clone (deep) {  var objectClone = new this.constructor();  for (var property in this)    if (!deep)      objectClone[property] = this[property];    else if (typeof this[property] == 'object')      objectClone[property] = this[property].clone(deep);    else      objectClone[property] = this[property];  return objectClone;}Object.prototype.clone = clone;




///////////////////////////////////Nodes addition///////////////////////////////////

//Function to add a new input node to the list of nodes
var defaultInputNode=[{name:'Name of the input',type:'integer',mandatory:'optional',spec:'definition of input limits',description:'Any special comment here'}];
function addInputNode()
{
	//need to clone the node to make the node independant
	var aClone = defaultInputNode.clone(true);
//	YAHOO.log(aClone.length);
	
	//Add the Node to the tree
	var root = inputTree.getRoot(); 
	inputTree.loadNodes(aClone,root);
	inputTree.draw(); 
}
//Function to add a new input node to the list of nodes
var defaultOutputNode=[{
	name:'Name of the output',
	type:'integer',
	mandatory:'optional',
	min:'0',
	max:'1',
	spec:'definition of output limits',
	description:'Any special comment here'
	}];
	
function addOutputNode()
{
	//need to clone the node to make the node independant
	var aClone = defaultOutputNode.clone(true);
//	YAHOO.log(aClone.length);
	
	//Add the Node to the tree
	var root = outputTree.getRoot(); 
	outputTree.loadNodes(aClone,root);
	outputTree.draw(); 
}



//Function to add a new input node to the list of nodes
var defaultOutputGroup=[{
	name:'Name of the group',
	mandatory:'optional',
	min:'0',
	max:'1',
	description:'What is the purpose of the group',        child:[{        	name:'Name of the output',        	type:'integer',
        	mandatory:'mandatory',
        	min:1,
        	max:1,        	spec:'',
        	description:'What is the purpose of this output'    	}]
    }];
    
function addOutputGroup()
{
	//need to clone the node to make the node independant
	var aClone = defaultOutputGroup.clone(true);
//	YAHOO.log(aClone.length);
	
	//Add the Node to the tree
	var root = outputTree.getRoot(); 
	outputTree.loadNodes(aClone,root);
	outputTree.draw(); 
}




///////////////////////////////////Nodes addition///////////////////////////////////

function getMessageDefinition()
{
	//input definition
	var MessageDefinition = '{"inputDefinition":';
	MessageDefinition += inputTree.getTreeJSONData();
	
	//output definition
	MessageDefinition += ',"outputDefinition":';
	MessageDefinition += outputTree.getTreeJSONData();	
	

	
	
	//We put the examples list
	var sb = [];
	if(inputTreeEx.length >0){
		for(var i=0;i<inputTreeEx.length;i++) {
			var temp = getExampleDefinition(i);
			if(temp) sb[sb.length] = temp;
		}	
		MessageDefinition += ',"examplesDefinition":[';
		MessageDefinition += sb.join(",");
		MessageDefinition += ']';
	}


	var ErrorListData = YAHOO.draftrack.errorsList.oDS.getRecordSet();
	var sb = [];
	if(ErrorListData.getLength() > 0) {
		for(var i=0;i<ErrorListData.getLength();i++) {
			var tempData = ErrorListData.getRecord(i).getData();
			sb[sb.length] = '{"id": ' + tempData.id + ',"text": "' + tempData.text +'" }';
		}	
		MessageDefinition += ',"errorsList":[';
		MessageDefinition += sb.join(",");
		MessageDefinition += ']';
	}

	
	
	MessageDefinition += '}';
	
	return MessageDefinition;
	
}








var exampleCounts = 0;
var outputTreeEx = [];
var inputTreeEx = [];
var APIBaseURL = document.getElementById('APIBaseURL').innerHTML;


function createNewExample()
{
	
	var list = document.getElementById('examplesList');
	
	exampleBox = list.appendChild(document.createElement("div"));
	exampleBox.id= 'example' + exampleCounts;
	exampleBox.className =  "messageExample";
	
	var sb = [];

	sb[sb.length] = '<h2 class="messageExampleDefinition" id="exampleTitle' + exampleCounts + '">';
	sb[sb.length] = '<div id="example' + exampleCounts + 'SectionShowHideSectionBox" class="hideSection" onClick="showHideSection(\'example' + exampleCounts + 'Section\')">&nbsp;</div>';
	sb[sb.length] = 'Example '+ exampleCounts  +' <button onClick="removeExample(' + exampleCounts + ')">Remove Example</button></h2>';
	
	sb[sb.length] = '<div id="example' + exampleCounts + 'Section">';
	
	sb[sb.length] = '<h3>Example Description</h3>';
	sb[sb.length] = '<textarea cols="50" id="exampleDefinition' + exampleCounts + '"></textarea>';
	sb[sb.length] = '<h3>Inputs</h3>';
	sb[sb.length] = '<div id="treeInputEx'+ exampleCounts +'"></div>';
		
	sb[sb.length] = '<h3>Outputs</h3>';
	sb[sb.length] = '<div id="treeOutputEx'+ exampleCounts +'"></div>';

	sb[sb.length] = '<h3>Visualisation &nbsp; <button onClick="visualizeExample('+ exampleCounts +')">View data</button></h3>';
	sb[sb.length] = '<div id="visualize'+ exampleCounts +'"></div>';
	
	sb[sb.length] = '</div>';

	
	exampleBox.innerHTML += sb.join("");	

//We retrieve the message definition
var dataString = getMessageDefinition();
var prod = YAHOO.lang.JSON.parse(dataString);

//Generating inputExampleTree
inputTreeEx[exampleCounts] = new YAHOO.drafTrack.exampleEditorTree('treeInputEx'+ exampleCounts ,oInputExampleConfigs); var root = inputTreeEx[exampleCounts].getRoot(); 
	
inputTreeEx[exampleCounts].loadNodes(prod.inputDefinition,root);inputTreeEx[exampleCounts].draw(); 


//Generating outputExampleTree
outputTreeEx[exampleCounts] = new YAHOO.drafTrack.exampleEditorTree('treeOutputEx'+ exampleCounts ,oOutputExampleConfigs); var root = outputTreeEx[exampleCounts].getRoot(); 
	
outputTreeEx[exampleCounts].loadNodes(prod.outputDefinition,root);outputTreeEx[exampleCounts].draw(); 

exampleCounts++;
//oOutputExampleConfigs 
}






function getExampleDefinition(exampleId)
{
	if(!inputTreeEx[exampleId]) return false;
	
	var exampleDefinition = '{';
	
	exampleDefinition += '"definition":' + YAHOO.lang.JSON.stringify(document.getElementById('exampleDefinition'+ exampleId).value)+',';
	exampleDefinition += '"inputValues":';
	exampleDefinition += inputTreeEx[exampleId].getTreeJSONData();
	exampleDefinition += ',"outputValues":';
	exampleDefinition += outputTreeEx[exampleId].getTreeJSONData();	
	exampleDefinition += '}';
	return exampleDefinition;
}

function visualizeExample(exampleId)
{
	var inputsStr = inputTreeEx[exampleId].getTreeJSONData();
	
	document.getElementById('visualize'+ exampleId).innerHTML = inputs;
	
	try { var inputs = YAHOO.lang.JSON.parse(inputsStr); } 	catch (e) {  alert("Cannot decode inputs list");return; }

	var sb = [];
		
	for(var inputName in inputs )
	{
		if(inputName == 'clone') continue;
		sb[sb.length]= inputName + '/'+inputs[inputName];
	}
	var parameters = sb.join('/');
	YAHOO.log(inputs);
	var inputURL =  APIBaseURL + parameters;
	document.getElementById('visualize'+ exampleId).innerHTML = '<b>input URL: </b><div class="exampleOutput" id="exampleinput' + exampleId+'">' + inputURL + '</div>';
	
	document.getElementById('visualize'+ exampleId).innerHTML +='<b>output JSON string: </b><div class="exampleOutput" id="exampleJSON' + exampleId+'">'+ outputTreeEx[exampleId].getTreeJSONData()+ '</div>';
	
	document.getElementById('visualize'+ exampleId).innerHTML +='<b>output PHP serialized string: </b><div class="exampleOutput" id="exampleserializedphp' + exampleId+'">'+ outputTreeEx[exampleId].getTreeJSONData()+ '</div>';
		
	makeRequest(exampleId,'serializedphp');

}



//connection to retrieve PHP formatting of the stringvar handleSuccess = function(o){
		if(o.responseText !== undefined){
		//we parse the string
		var message = YAHOO.lang.JSON.parse(o.responseText);
		if(message.status == 'KO') alert('an error occured while generating example');
		
		//We get the DIV
		div = document.getElementById('example'+o.argument[0]+o.argument[1]);
			div.innerHTML = message.formattedString;	}};var handleFailure = function(o){		YAHOO.log("The failure handler was called.  tId: " + o.tId + ".", "info", "example");	if(o.responseText !== undefined){		div.innerHTML = "<li>Transaction id: " + o.tId + "</li>";		div.innerHTML += "<li>HTTP status: " + o.status + "</li>";		div.innerHTML += "<li>Status code message: " + o.statusText + "</li>";	}};function makeRequest(exampleId,type){
	var sUrl = document.getElementById('JSONConversionURL').innerHTML;	var postData = 'outputFormat=' + type + '&JSONString=' + outputTreeEx[exampleId].getTreeJSONData();	
	var callback =	{ 	 success:handleSuccess, 	 failure:handleFailure, 	 argument:[type,exampleId]	};
	
	var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);}








function removeExample(exampleId)
{
	var el= document.getElementById('example'+exampleId);
	el.innerHTML = '';
	el.className='';
	outputTreeEx[exampleId] = '';
	inputTreeEx[exampleId] = '';
}







//////////////////  error messages related functions ////////////////////////////////


function errorsSearchListInit() {
YAHOO.namespace("draftrack.errorContainer");	


YAHOO.draftrack.errorContainer = function() {
    	// Use an XHRDataSource
    	var oDS = new YAHOO.util.XHRDataSource("/draftrack/draftrackfe/public/apidesigner/index/searcherror/");
    	// Set the responseType
    	oDS.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
    	// Define the schema of the delimited results
		oDS.responseSchema = { 
	        resultsList : "errors", 
	        fields : ["id","text","creatorEmail","creationDate"] 
	    }; 

    	// Instantiate the AutoComplete
    	var oAC = new YAHOO.widget.AutoComplete("searchString", "searchStringAutoCompResponse", oDS);
 
     	// The webservice needs additional parameters
    	oAC.generateRequest = function(sQuery) {
       		return "searchString/" + sQuery+'/' ;
    	};
    	oAC.queryDelay = 0.8;
    	oAC.resultTypeList = false; 
    	oAC.alwaysShowContainer = true;
    	
    	oAC.formatResult = function(oResultItem, sQuery) {  
	        var sText = oResultItem.text; 
	        var sId = oResultItem.id;  
	        var sMarkup = sId + " - " + sText; 
	        return (sMarkup); 
	    };
		
		//Triggers when the user selects a line
		var itemSelectHandler = function(sType, aArgs) {
			var oData = aArgs[2]; // object literal of data for the result
			YAHOO.draftrack.errorsList.oDS.addRow(oData);
			YAHOO.draftrack.errorContainer.oESP.hide();
		};
   		
   		oAC.itemSelectEvent.subscribe(itemSelectHandler); 


		//triggers when data is returned by the server
		var dataReturnHandler = function  ( sType , aArgs ) {
			var oAutoComp = aArgs[0]; 
	        var sQuery = aArgs[1]; 
	        var aResults = aArgs[2]; 
	 		
	        if(aResults.length == 0) {
	            oAutoComp.setBody('<div id=\"statescontainerdefault\">No matching results<button onclick="YAHOO.draftrack.errorContainer.odECP()">Create new message</button></div>');
	        }
		}		
		
		oAC.dataReturnEvent.subscribe(dataReturnHandler);
		
   
	// Instantiate the Dialog
	var newErrorSearchPanel = new YAHOO.widget.Dialog("newErrorSearchPanel", 
							{ width : "30em",
							  visible : false, 
							  constraintoviewport : true
							});
	
	// Render the Dialog
	newErrorSearchPanel.render();


	// Instantiate the Dialog
	var newErrorPanel = new YAHOO.widget.Dialog("newErrorPanel", 
							{ width : "400px",
							  visible : false, 
							  constraintoviewport : true
							});

var handleSubmit = function() {
	this.submit();
};

var handleSuccess = function(o) {
	var response = YAHOO.lang.JSON.parse(o.responseText);
	if('KO' == response.status) {
		alert('an error occured while saving the error message: ' + response.error.message);
	} else {
		YAHOO.draftrack.errorsList.oDS.addRow(response.error);
	}
	
};

var handleFailure = function(o) {
	alert('an error occured while saving the error message: ' + o.status);
};

newErrorPanel.callback = { success: handleSuccess,
						failure: handleFailure };

	
	// Render the Dialog
	newErrorPanel.render();
	
	var displayErrorCreationPanel = function() {
		this.oESP.hide();
		this.oEP.show();	
	}
		
	return {
        	oESP: newErrorSearchPanel,
        	oEP: newErrorPanel,
        	odECP:displayErrorCreationPanel,
        	osubmit:handleSubmit
    	};
	}();
	
YAHOO.util.Event.addListener("displayErrorCreationPanel", "click", YAHOO.draftrack.errorContainer.oESP.show, YAHOO.draftrack.errorContainer.oESP, true);

} //end errorsSearchListInit
	
YAHOO.util.Event.onDOMReady(errorsSearchListInit);



function errorsListInit() {
YAHOO.namespace("draftrack.errorsList");
YAHOO.draftrack.errorsList = function() { 
var ErrorsList = data.errorsList;

   var errorColumnDefs = [
            {key:"id", sortable:true, resizeable:true,size:"400px"},
            {key:"text", resizeable:true}
        ];

  var errorDataSource = new YAHOO.util.DataSource(ErrorsList);
        errorDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        errorDataSource.responseSchema = {
            fields: ["id","text"]
        };

   var errorDataTable = new YAHOO.widget.DataTable("errorsListTable",
                errorColumnDefs, errorDataSource);
              
	return { 
	            oDT: errorDataSource, 
	            oDS: errorDataTable 
	        }; 
	    }();
	
	/*
	var testData = YAHOO.draftrack.errorsList.oDS.getRecordSet()
	testData.getLength();
	testData.getRecord(0).getData()
	*/
	    
} //end errorsListInit


YAHOO.util.Event.onDOMReady(errorsListInit);
